package TestPaperSystem.service.impl;

import TestPaperSystem.Dto.PageUtils_VO;
import TestPaperSystem.entity.Exam;
import TestPaperSystem.mapper.ExamMapper;
import TestPaperSystem.service.ExamService;
import TestPaperSystem.utils.DateGetter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwj
 * @since 2023-03-25
 */
@Service
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {

    @Resource
    ExamMapper examMapper;

    @Override
    public Page<Exam> getListByExam(PageUtils_VO page) throws Exception{
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        if(page.getId().equals("")){
            queryWrapper.eq("open_type",0)
                    .le("start_time", DateGetter.getInstance().getCurrentTime())
                    .ge("end_time",DateGetter.getInstance().getCurrentTime())
                    .or()
                    .isNull("start_time");
        }else{
            queryWrapper.eq("id",page.getId());

        }
        Page<Exam> examPage = examMapper.selectPage(new Page<Exam>(page.getCurrentPage(), page.getSize()), queryWrapper);

        long counts = examMapper.selectCount(queryWrapper);

        examPage.setTotal(counts);
        return examPage;
    }

    @Override
    public Boolean saveData(Exam exam) {
        UpdateWrapper<Exam> updateWrapper = new UpdateWrapper<>();
        if(exam.getId() == null){
            return this.save(exam);
        }else{
            updateWrapper.lambda().eq(Exam::getId,exam.getId());
            return this.update(exam,updateWrapper);
        }
    }

    @Override
    public Page getSelfList(PageUtils_VO page) {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(Exam::getUserId,page.getId());
        Page<Exam> page_db = examMapper.selectPage(new Page(page.getCurrentPage(), page.getSize()), queryWrapper);

        return page_db;
    }

    @Override
    public Page getExamAndConfig(PageUtils_VO page) {

        Page page_db = new Page();
        page_db.setRecords(examMapper.getExamAndConfig((page.getCurrentPage()-1) * page.getSize() ,page.getSize() , page.getId()));
        return page_db;
    }
}
